
#include <stdint.h>
#include "misc.h"
#include "os.h"
#include "memory.h"
#include "device.h"

#if CONFIG_CONSOLE
#include <stdio.h>
#include "console.h"
#endif

#include "debug.h"

#if CONFIG_FS
#include "vfs.h"
#endif

static void nvic_configuration(void) {
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
}

static void systick_init(void) {
	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
    SysTick->LOAD = SystemCoreClock/8/OSCfg_TickRate_Hz - 1;
	SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk;
	SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
}

#if CONFIG_CONSOLE

static void show_sysinfo(void) {
    printf("%s Build %s\r\n", SDKVERSION, BUILDDATE);
    printf("Firmware: %s\r\n", FW_NAME);
    printf("Platform: %s\r\n", PLATNAME);
    printf("Board:    %s\r\n", BOARDNAME);
}

static void show_logo(void) {
    printf("    ____                               _          \r\n");
    printf("   / __ \\  ____ _   _____ _      __   (_)   ____  \r\n");
    printf("  / / / / / __ `/  / ___/| | /| / /  / /   / __ \\ \r\n");
    printf(" / /_/ / / /_/ /  / /    | |/ |/ /  / /   / / / / \r\n");
    printf("/_____/  \\__,_/  /_/     |__/|__/  /_/   /_/ /_/  \r\n");
    printf("\r\n");
}

#endif

void system_init(void) {
    OS_ERR err = OS_ERR_NONE;
    nvic_configuration();
    systick_init();
    OSInit(&err);
    CPU_Init();
#if OS_CFG_SCHED_ROUND_ROBIN_EN > 0u
    OSSchedRoundRobinCfg(DEF_ENABLED, 1, &err);
#endif
    memory_init();
    device_init();
#if CONFIG_CONSOLE
	uart_cfg_t uart_cfg = 
	{
		.baud_rate = 115200,
		.word_length = UART_WORDLENGTH_8,
		.stop_bits = UART_STOPBITS_1,
		.parity = UART_PARITY_NO,
        .mode = UART_MODE_RX_TX,
		.hardware_flowcontrol = UART_HWFC_None,
        .rx_buffer_size = 512
	};
    console_init((uart_port_e)CONFIG_CONSOLE_DEV_PORT, &uart_cfg);
#if CONFIG_CONSOLE_LOG
    debug_init();
#endif
    show_sysinfo();
    show_logo();
#endif
#if CONFIG_FS
    vfs_init();
#endif
}

#if CONFIG_CONSOLE
dev_export(DEV_CLASS_UART, CONFIG_CONSOLE_DEV_NAME, CONFIG_CONSOLE_DEV_PORT);
#endif
